//
//  TexTureImageViewController.m
//  OpenGL_三角形
//
//  Created by user on 2018/10/9.
//  Copyright © 2018年 陈振旭. All rights reserved.
//

#import "TexTureImageViewController.h"

//设置顶点数组 和 索引数组
static GLfloat Vertices[] = {
    
    0.5, -0.5, 0.0f,    1.0f, 0.0f, //右下(x,y,z坐标 + s,t纹理)
    -0.5, 0.5, 0.0f,    0.0f, 1.0f, //左上
    -0.5, -0.5, 0.0f,   0.0f, 0.0f, //左下
    0.5, 0.5, 0.0f,    1.0f, 1.0f, //右上
};

//顶点索引
static GLuint indices[] = {
    0,1,2,
    1,3,0
};

@interface TexTureImageViewController ()

@property (nonatomic, strong) EAGLContext *context;

@property (nonatomic, strong) GLKBaseEffect *baseEffect;

@end

@implementation TexTureImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    [EAGLContext setCurrentContext:_context];
    if (!_context) {
       NSAssert(_context && [EAGLContext setCurrentContext:_context], @"初始化GL环境失败");
    }
    
    GLKView *view = (GLKView *)self.view;
    view.drawableDepthFormat = GLKViewDrawableColorFormatRGBA8888;
    view.context = _context;
    
    
    GLuint verticesBuffer;
    glGenBuffers(1, &verticesBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, verticesBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STREAM_DRAW);
    
    GLuint indeicesBuffer;
    glGenBuffers(1, &indeicesBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indeicesBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STREAM_DRAW);
    
    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
    
    glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, (GLfloat *)NULL + 0);
    glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, (GLfloat *)NULL + 3);
    
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"ic_dog" ofType:@"jpeg"];
   
    NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], GLKTextureLoaderOriginBottomLeft, nil];
    
    GLKTextureInfo* textureInfo = [GLKTextureLoader textureWithContentsOfFile:filePath options:options error:nil];
    
    _baseEffect = [[GLKBaseEffect alloc] init];
    _baseEffect.texture2d0.enabled = GL_TRUE;
    _baseEffect.texture2d0.name = textureInfo.name;
}

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
    [_baseEffect prepareToDraw];
    
    glClearColor(0.3f, 0.6f, 1.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    int count = sizeof(indices) / sizeof(indices[0]);
    glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_INT, 0);
}


@end
